<template>
  <div class="min-h-screen bg-gray-50 ">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Header -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <h1 class="text-2xl font-bold text-gray-900">充电调度优先级管理（异常修正）</h1>
            <span class="ml-4 text-sm text-gray-500">当前车辆: {{ currentVehicle?.id }}</span>
          </div>
          <div class="flex space-x-2">
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button type="primary" @click="showRulesModal = true">调度规则</el-button>
          </div>
        </div>
      </div>

      <!-- Priority Calculation -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">优先级计算</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div class="bg-gray-50 p-4 rounded-lg shadow-sm">
              <div class="text-sm text-gray-500 mb-2">
                SOC 异常程度因子（HSP）
                <el-button type="text" size="small" @click="showHSPModal = true">计算依据</el-button>
              </div>
              <div class="text-xl font-bold text-orange-600">{{ hspFactor }}</div>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg shadow-sm">
              <div class="text-sm text-gray-500 mb-2">初始调度优先级</div>
              <div class="text-xl font-bold text-blue-600">{{ initialPriority }}</div>
              <div class="text-xs text-gray-400 mt-1">基于 SOC={{ currentVehicle?.soc }}% 生成</div>
            </div>
            <div class="bg-gray-50 p-4 rounded-lg shadow-sm">
              <div class="text-sm text-gray-500 mb-2">惩罚系数（α）</div>
              <div class="flex items-center space-x-2">
                <el-slider
                    v-model="penaltyFactor"
                    :min="0.1"
                    :max="1.0"
                    :step="0.1"
                    class="flex-1"
                />
                <span class="text-lg font-bold text-purple-600 min-w-[3rem]">{{ penaltyFactor }}</span>
              </div>
              <div class="text-xs text-gray-400 mt-1">当前 α={{ penaltyFactor }}（默认）</div>
            </div>
          </div>

          <div class="bg-blue-50 p-4 rounded-lg">
            <div class="text-sm font-medium text-blue-800 mb-3">计算公式</div>
            <div class="bg-white p-3 rounded font-mono text-sm">
              修正后调度优先级 = 初始优先级 × (1 - α×HSP)
            </div>
            <div class="mt-3 text-sm text-blue-700">
              = {{ initialPriority }} × (1 - {{ penaltyFactor }}×{{ hspFactor }})
            </div>
            <div class="text-sm text-blue-700">
              = {{ initialPriority }} × {{ (1 - penaltyFactor * hspFactor).toFixed(2) }}
            </div>
            <div class="text-lg font-bold text-blue-800 mt-2">
              = {{ finalPriority }}
            </div>
          </div>
        </div>

        <div class="mt-4 p-4 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-lg">
          <div class="text-lg font-bold">
            初始 {{ initialPriority }} → 修正后 {{ finalPriority }}
            <span class="text-sm opacity-90">（下调 {{ Math.round((1 - finalPriority / initialPriority) * 100) }}%）</span>
          </div>
        </div>
      </div>

      <!-- Dispatch Operations -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">调度操作</h2>
        <div class="flex space-x-4">
          <el-button
              type="primary"
              size="large"
              :loading="isAddingToQueue"
              @click="addToQueue"
          >
            {{ isAddingToQueue ? '加入队列中...' : '加入待调度队列' }}
          </el-button>
        </div>

        <div v-if="queueStatus" class="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
          <div class="text-sm font-medium text-green-800">{{ queueStatus }}</div>
        </div>

        <div class="mt-4">
          <div class="text-sm font-medium text-gray-700 mb-2">队列更新日志</div>
          <div class="space-y-1">
            <div v-for="log in queueLogs" :key="log.id" class="text-sm text-gray-600">
              {{ log.timestamp }}: {{ log.message }}
            </div>
          </div>
        </div>
      </div>

      <!-- Dispatch Queue -->
      <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-gray-900">待调度队列</h2>
          <div class="flex space-x-2">
            <el-button
                type="primary"
                size="small"
                :loading="isRefreshing"
                @click="refreshQueue"
            >
              <el-icon><Refresh /></el-icon>
              {{ isRefreshing ? '同步中...' : '队列刷新' }}
            </el-button>
            <el-button
                size="small"
                @click="showBatchAdjustModal = true"
            >
              批量调整
            </el-button>
          </div>
        </div>

        <!-- 分组显示队列 -->
        <div class="space-y-4">
          <!-- 高风险组 -->
          <div class="border-l-4 border-l-red-500 bg-red-50 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <h3 class="font-medium text-red-900">
                高风险组 ({{ highRiskQueue.length }}辆)
              </h3>
              <el-button
                  size="small"
                  type="danger"
                  @click="adjustGroupPriority('high', 0.1)"
              >
                优先级 +0.1
              </el-button>
            </div>
            <div class="space-y-2">
              <div
                  v-for="(item, index) in highRiskQueue"
                  :key="item.id"
                  class="flex items-center justify-between p-3 bg-white border rounded-lg hover:bg-gray-50"
              >
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <span class="font-medium">{{ index + 1 }}.</span>
                    <span class="font-medium">{{ item.id }}</span>
                    <span class="text-gray-500">{{ item.model }}</span>
                    <span class="text-sm text-gray-400">SOC: {{ item.soc }}%</span>
                    <span class="font-bold text-red-600">优先级: {{ item.priority }}</span>
                    <el-tooltip
                        v-if="item.status === 'abnormal'"
                        :content="`因 HSP=${item.hspFactor}，优先级从 ${item.originalPriority} 下调至 ${item.priority}`"
                        placement="top"
                    >
                      <span class="text-sm text-orange-600 cursor-help">[{{ item.reason }}]</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 中风险组 -->
          <div class="border-l-4 border-l-yellow-500 bg-yellow-50 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <h3 class="font-medium text-yellow-900">
                中风险组 ({{ warningRiskQueue.length }}辆)
              </h3>
              <el-button
                  size="small"
                  type="warning"
                  @click="adjustGroupPriority('warning', 0.05)"
              >
                优先级 +0.05
              </el-button>
            </div>
            <div class="space-y-2">
              <div
                  v-for="(item, index) in warningRiskQueue"
                  :key="item.id"
                  class="flex items-center justify-between p-3 bg-white border rounded-lg hover:bg-gray-50"
              >
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <span class="font-medium">{{ highRiskQueue.length + index + 1 }}.</span>
                    <span class="font-medium">{{ item.id }}</span>
                    <span class="text-gray-500">{{ item.model }}</span>
                    <span class="text-sm text-gray-400">SOC: {{ item.soc }}%</span>
                    <span class="font-bold text-yellow-600">优先级: {{ item.priority }}</span>
                    <el-tooltip
                        v-if="item.status === 'abnormal'"
                        :content="`因 HSP=${item.hspFactor}，优先级从 ${item.originalPriority} 下调至 ${item.priority}`"
                        placement="top"
                    >
                      <span class="text-sm text-orange-600 cursor-help">[{{ item.reason }}]</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 低风险组 -->
          <div class="border-l-4 border-l-green-500 bg-green-50 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <h3 class="font-medium text-green-900">
                低风险组 ({{ lowRiskQueue.length }}辆)
              </h3>
              <el-button
                  size="small"
                  type="success"
                  @click="adjustGroupPriority('low', 0.02)"
              >
                优先级 +0.02
              </el-button>
            </div>
            <div class="space-y-2">
              <div
                  v-for="(item, index) in lowRiskQueue"
                  :key="item.id"
                  class="flex items-center justify-between p-3 bg-white border rounded-lg hover:bg-gray-50"
              >
                <div class="flex-1">
                  <div class="flex items-center space-x-2">
                    <span class="font-medium">{{ highRiskQueue.length + warningRiskQueue.length + index + 1 }}.</span>
                    <span class="font-medium">{{ item.id }}</span>
                    <span class="text-gray-500">{{ item.model }}</span>
                    <span class="text-sm text-gray-400">SOC: {{ item.soc }}%</span>
                    <span class="font-bold text-green-600">优先级: {{ item.priority }}</span>
                    <el-tooltip
                        v-if="item.status === 'abnormal'"
                        :content="`因 HSP=${item.hspFactor}，优先级从 ${item.originalPriority} 下调至 ${item.priority}`"
                        placement="top"
                    >
                      <span class="text-sm text-orange-600 cursor-help">[{{ item.reason }}]</span>
                    </el-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- HSP 因子对比图 -->
        <div class="mt-6 bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">异常程度对比</h3>
          <div class="h-48">
            <v-chart :option="hspCompareOption" class="w-full h-full" />
          </div>
        </div>
      </div>
    </div>

    <!-- Batch Adjust Modal -->
    <el-dialog v-model="showBatchAdjustModal" title="批量调整优先级" width="500px">
      <el-form :model="batchAdjustData" label-width="120px">
        <el-form-item label="调整组别">
          <el-select v-model="batchAdjustData.group" placeholder="请选择组别">
            <el-option label="高风险组" value="high" />
            <el-option label="中风险组" value="warning" />
            <el-option label="低风险组" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="调整幅度">
          <el-input-number
              v-model="batchAdjustData.adjustment"
              :min="-0.5"
              :max="0.5"
              :step="0.01"
              :precision="2"
          />
        </el-form-item>
        <el-form-item label="调整原因">
          <el-input
              v-model="batchAdjustData.reason"
              type="textarea"
              placeholder="请输入调整原因"
          />
        </el-form-item>
      </el-form>
      <div class="mb-4 p-3 bg-blue-50 rounded-lg">
        <div class="text-sm text-blue-800">
          将对 {{ getGroupCount(batchAdjustData.group) }} 辆车辆进行优先级调整
        </div>
      </div>
      <template #footer>
        <div class="flex justify-end space-x-2">
          <el-button @click="showBatchAdjustModal = false">取消</el-button>
          <el-button type="primary" @click="handleBatchAdjust">确认调整</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Modals -->
    <TechnicalModal
        v-model="showRulesModal"
        title="调度规则"
        :sections="rulesSection"
    />

    <TechnicalModal
        v-model="showHSPModal"
        title="HSP 计算依据"
        :sections="hspSections"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { Refresh } from '@element-plus/icons-vue'
import TechnicalModal from '@/components/TechnicalModal.vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
])

const router = useRouter()
const store = useAppStore()

const currentVehicle = computed(() => store.currentVehicle)
const penaltyFactor = ref(0.8)
const isAddingToQueue = ref(false)
const isRefreshing = ref(false)
const queueStatus = ref('')
const showRulesModal = ref(false)
const showHSPModal = ref(false)
const showBatchAdjustModal = ref(false)

const batchAdjustData = ref({
  group: '',
  adjustment: 0,
  reason: ''
})

const queueLogs = ref([
  {
    id: 1,
    timestamp: '2025-05-06 10:42',
    message: 'BYD-HAN-123456 加入队列，触发优先级重排'
  }
])

const highRiskQueue = computed(() =>
    store.dispatchQueue.filter(item => {
      const vehicle = store.vehicles.find(v => v.id === item.id)
      return vehicle?.riskLevel === 'high'
    })
)

const warningRiskQueue = computed(() =>
    store.dispatchQueue.filter(item => {
      const vehicle = store.vehicles.find(v => v.id === item.id)
      return vehicle?.riskLevel === 'warning'
    })
)

const lowRiskQueue = computed(() =>
    store.dispatchQueue.filter(item => {
      const vehicle = store.vehicles.find(v => v.id === item.id)
      return vehicle?.riskLevel === 'low'
    })
)

const hspCompareOption = computed(() => ({
  title: {
    text: 'HSP 异常程度因子对比',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: store.dispatchQueue.map(item => item.id),
    axisLabel: {
      rotate: 45
    }
  },
  yAxis: {
    type: 'value',
    name: 'HSP 因子',
    min: 0,
    max: 1
  },
  series: [{
    type: 'bar',
    data: store.dispatchQueue.map(item => ({
      value: item.hspFactor,
      itemStyle: {
        color: item.hspFactor > 0.5 ? '#ef4444' :
            item.hspFactor > 0.2 ? '#f59e0b' : '#22c55e'
      }
    }))
  }]
}))

const hspFactor = computed(() => {
  // 计算 HSP 因子：|跳变幅度-正常阈值|/(最大阈值-最小阈值)/2
  const jumpMagnitude = 3.5 // 当前跳变幅度
  const normalThreshold = 1.0 // 正常阈值
  const maxThreshold = 2.0 // 最大阈值
  const minThreshold = 0.0 // 最小阈值

  return Math.round((Math.abs(jumpMagnitude - normalThreshold) / (maxThreshold - minThreshold) / 2) * 100) / 100
})

const initialPriority = computed(() => {
  // 基于 SOC 计算初始优先级
  const soc = currentVehicle.value?.soc || 0
  return Math.round((1 - soc / 100) * 100) / 100
})

const finalPriority = computed(() => {
  return Math.round(initialPriority.value * (1 - penaltyFactor.value * hspFactor.value) * 100) / 100
})

const rulesSection = [
  {
    title: '异常车辆优先级修正规则',
    content: '基于 HSP 因子下调初始优先级，确保异常车辆不会获得过高的调度优先级。'
  },
  {
    title: '优先级计算方法',
    content: '修正后优先级 = 初始优先级 × (1 - α×HSP)，其中 α 为惩罚系数，HSP 为异常程度因子。'
  },
  {
    title: '队列排序规则',
    content: '队列按修正后优先级从高到低排序，同时考虑车辆的紧急程度和充电需求。'
  }
]

const hspSections = computed(() => [
  {
    title: '计算公式',
    content: 'HSP = |跳变幅度-正常阈值|/(最大阈值-最小阈值)/2'
  },
  {
    title: '具体计算',
    content: `HSP = |3.5%-1.0%|/(2.0%-0.0%)/2 = ${hspFactor.value}`
  },
  {
    title: '含义解释',
    content: 'HSP 值越大表示异常程度越高，对初始优先级的惩罚越大。'
  }
])

const addToQueue = () => {
  isAddingToQueue.value = true

  setTimeout(() => {
    isAddingToQueue.value = false
    queueStatus.value = '已加入队列！队列位置：第 1 位（基于修正后优先级）'

    // 添加日志
    queueLogs.value.unshift({
      id: Date.now(),
      timestamp: new Date().toLocaleString('zh-CN'),
      message: `${currentVehicle.value?.id} 加入队列，优先级: ${finalPriority.value}`
    })

    // 5秒后清除状态
    setTimeout(() => {
      queueStatus.value = ''
    }, 5000)
  }, 1500)
}

const refreshQueue = () => {
  isRefreshing.value = true

  setTimeout(() => {
    isRefreshing.value = false
    queueLogs.value.unshift({
      id: Date.now(),
      timestamp: new Date().toLocaleString('zh-CN'),
      message: '队列刷新完成，3/5 车辆已更新'
    })
  }, 1000)
}

const adjustGroupPriority = (group: string, adjustment: number) => {
  let count = 0
  const groupName = group === 'high' ? '高风险组' :
      group === 'warning' ? '中风险组' : '低风险组'

  store.dispatchQueue.forEach(item => {
    const vehicle = store.vehicles.find(v => v.id === item.id)
    if (vehicle?.riskLevel === group) {
      item.priority = Math.round((item.priority + adjustment) * 100) / 100
      count++
    }
  })

  queueLogs.value.unshift({
    id: Date.now(),
    timestamp: new Date().toLocaleString('zh-CN'),
    message: `${groupName} ${count} 辆车辆优先级调整 ${adjustment > 0 ? '+' : ''}${adjustment}`
  })

  ElMessage.success(`${groupName}优先级已调整`)
}

const getGroupCount = (group: string) => {
  if (!group) return 0
  return store.dispatchQueue.filter(item => {
    const vehicle = store.vehicles.find(v => v.id === item.id)
    return vehicle?.riskLevel === group
  }).length
}

const handleBatchAdjust = () => {
  adjustGroupPriority(batchAdjustData.value.group, batchAdjustData.value.adjustment)

  queueLogs.value.unshift({
    id: Date.now(),
    timestamp: new Date().toLocaleString('zh-CN'),
    message: `批量调整: ${batchAdjustData.value.reason}`
  })

  showBatchAdjustModal.value = false
  batchAdjustData.value = { group: '', adjustment: 0, reason: '' }
}

onMounted(() => {
  if (!currentVehicle.value) {
    router.push('/monitor')
  }
})
</script>